<template><!--提交记录-->
	<div id="test">
    <!--<title-top :fnlist="initObj.Fnlist"></title-top>-->
    <table-body :options="initObj"></table-body>
  </div>
</template>
<script>
//	import Cookies from 'js-cookie'
import {submitRecord} from '@/api/compitionStatic'
import {modifyUserSubmitRecordStatus, queryCtfTarget,queryTargetAllot,getTargetTeamList_new,getTargetTeamList} from '@/api/drill_compete'
import tableBody from './tableListComponent'
import groupMixin from "@/mixin/groupMixin"
export default {
    name: 'scenes',
    props:['sceneId', 'poll', 'type', 'showStatus', 'isBasicScore','touchType'],
    mixins: [groupMixin],
	data(){
    let isRightSel = [
          {
            id:'1',
            name:'正确'
          },
          {
            id:'0',
            name:'错误'
          }
        ]// 只有夺旗赛有作弊功能，其他赛没有
    let pName = this.$route.query.fromMenu
    let path = this.$route.path
    console.log('----------this.$route.path----------',path)
    
    // if(pName.includes('ctfContest')){
    // stDrill  渗透演练    ctfContest夺旗赛 // 'awdDrill' 对抗没有 24763
    if(['ctfContest','stDrill'].includes(pName)){
      isRightSel.push( { // 只有夺旗赛 和 渗透有作弊功能，其他赛没有
        id:'3',
        name:'作弊'
      })
    }
    
    
      
    const d = function(val){
      this.getAttackSuccess(null,null,val)
    }.bind(this);
    const cc = function(val){
      this.isright = val;
      this.getAttackSuccess();
    }.bind(this)
	  	return {
            questionList: [],
            topicsList: [],
	  	  initObj:{
            Button:[],
            Input:[
             /* {
                placeholder:'请输入gameBox名称',
                fnName:b,
              }*/
            ],
            Select:[
                {
                    optionsValue: [],
                    placeholder: `请选择团队`,
                    fnName: this.getAttackSuccessById
                },
              {
                placeholder:'是否正确',
                optionsValue:isRightSel,
                fnName:cc,
              }
            ],
            DatePicker:{
              isShow:false,
              fnName:d,
            },
            Page:{
              total:0,
              currentPage:1,
              pageSize:10
            },
            Table:{
              listCol:[
//              {
//                type: 'index',
//                align: 'center',
//                ellipsis:true,
//                width:60
//              },
                {
                  title:'团队名称',
                  key:'teamName',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  placement:'top-left',
                  order:1,
                    width: 240
                },
                {
                  title:'提交者',
                  key:'userName',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:100
                },
                {
                  title: this.type === 7 ? '任务显示名称' : '题目',
                  key:'targetName',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:200
                },
                {
                  title:'提交时间',
                  key:'createTime',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:150
                },
                {
                  title:'提交内容 / 验证结果',
                  key:'content',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:250
                },
                {
                  title:'得分',
                  key:'score',
                  align:'center',
                  ellipsis:true,
                  placement:'top-right',
                  width:60,
                  render:(h,params) => {
                    return h('Tag',{
                      props:{
                         color:params.row.score > 0 ? (params.row.status == 2 ? 'var(--status-pre)' : 'var(--status-yes)') :'var(--status-pre)',
                         type:"border"
                      },
                  	on:{
                            click:()=>{
                              //this.showAddAndUpdate(params.row)
                            }
                        }
                  }, params.row.isRight == 1 ? (params.row.status == 2 ? 0 : params.row.score)  : 0 )
                  }
                },
                {
                  title:'是否正确',
                  key:'isRight',
                  align:'center',
                  ellipsis:true,
                  placement:'top-right',
                  render:(h,params) => {
                    return h('Tag',{ //夺旗赛，无法得知答题正确性，赛中显示不确定
                      props:{
                        color:this.type === 2 && this.touchType === 2 && this.poll ? 'var(--status-no)' : params.row.isRight == 1 ? (params.row.status == 2 ? 'var(--status-no)' : 'var(--status-yes)') : params.row.isRight == 3 ? 'var(--status-deling)': 'var(--status-no)',
                        type:"border"
                      },
                      on:{
                          click:()=>{
                            //this.showAddAndUpdate(params.row)
                          }
                      }
                    },this.type === 2 && this.touchType === 2 && this.poll ? '不确定' : params.row.isRight == 1 ? (params.row.status == 2 ? '错误' : '正确') : params.row.isRight == 3 ? '作弊' : '错误' )
                  }
                },
//              {
//                title:'周期开始时间',
//                key:'startTime',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//                render:(h,params)=>{
//                  return h('span', params.row.startTime||'无')
//                }
//              },
//              {
//                title:'周期结束时间',
//                key:'nextStartTime',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//                render:(h,params)=>{
//                  return h('span', params.row.nextStartTime||'无')
//                }
//              },
//              {
//                title:'得分',
//                key:'score',
//                align:'center',
//              },
//              {
//                title:'得分时间',
//                key:'scoreTime',
//                align:'center',
//              },
//              {
//                title:'提交内容',
//                key:'cancelstatus',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//                render: (h, params) => {
//                  return h('span', this.cancelstatusFilter(params.row.cancelstatus))
//                }
//              },
//              {
//                title:'错误原因',
//                key:'errorinfo',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//              },
//              {
//                title:'提交时间',
//                key:'submittime',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//              },
//              {
//                title:'是否正确',
//                key:'isright',
//                align:'center',
//                ellipsis:true,
//              }
              ],
              listData:[]
            },
            Fnlist:'getAttackSuccess',
        },
        //sencenId:'',
        selName:'',
        isright:'',
        status: '',
        timeout:{},
      }
	},
    components:{
//    'title-top':titleTop,
      'table-body':tableBody,
    },
    watch:{
        teamList(newValue) {
            this.initObj.Select[0].optionsValue = newValue
        },
        questionList(newValue) {
            if(this.type == 2){
                this.initObj.Select.splice(1, 0, {
                    placeholder: '请选择题目',
                    optionsValue: newValue,
                    fnName: this.getAttackSuccessByQuestion
                })
            }
        },
        topicsList(newValue) {
            if(this.type !== 2){
                this.initObj.Select.splice(1, 0, {
                    placeholder: '请选择题目',
                    optionsValue: newValue,
                    fnName: this.getAttackSuccessByTopics
                })
            }
        }
    },
    created(){
      if(this.type==0){
        this.initObj.Table.listCol.push( {
                  title:'提交周期',
                  key:'number',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:100,
                  render:(h,params) => {
                  	return h('span',params.row.number ? `第${params.row.number}周期` : '无')
                  }
                },)
      }
      if(this.type==8){
        this.initObj.Table.listCol.push( {
          title:'提交周期',
          key:'number',
          align:'center',
          ellipsis:true,
          tooltip:true,
          width:100,
          render:(h,params) => {
            return h('span',params.row.number ? `第${params.row.number}周期` : '无')
          }
        },)
        let index = this.initObj.Table.listCol.findIndex(item => item.title === '得分')
        if (index !== -1) {
          this.initObj.Table.listCol.splice(index, 1)
        }
      }
        if (this.showStatus && !this.isBasicScore&&this.type!=0) { // 非基础分模式才有撤销功能
            this.initObj.Select.push({
                placeholder:'是否撤销',
                optionsValue:
                    [
                        {
                            id:'2',
                            name:'撤销'
                        },
                        {
                            id:'1',
                            name:'未撤销'
                        }
                    ],
                fnName: this.byStatus
            })
        }
        if(this.type == 2 && !this.poll && !this.isBasicScore){ //夺旗赛、赛后、非基础分模式才有撤销功能
            this.initObj.Table.listCol.push({
                title:'是否撤销',
                align:'center',
                placement:'top-right',
                key:'sfcx',
                render:(h,params) => {
                    return h('Tag',{
                        props:{
                            color:params.row.tag == 0 || params.row.tag == 3 || params.row.status == 2 ? 'blue' : 'default',
                        },
                        style:{
                            marginRight:'5px'
                        }
                    },params.row.tag == 0 || params.row.tag == 3 || params.row.status == 2 ? '是' : '否')
                }
            })
            this.initObj.Table.listCol.push({
                title:'操作',
                align:'center',
                placement:'top-right',
                key:'action',
                opList:[
                  {
                    txt:(data) => {
                      return data.tag == 0 || data.tag == 3 || data.status == 2 ? '取消撤销' : '撤销'
                    },
                    title:(data) => {
                      return `你确定要${data.tag == 0 || data.tag == 3 || data.status == 2 ? '取消撤销' : '撤销'}吗?`
                    },
                    fun:(data) => {
                      this.modifyRecordStatus(data.id,data.status,data.tag, data.isRight)
                    },
                    disabled: this.isDisabled,
                    tooltip:true
                  }
                ],
                // render:(h,params) => {
                //     return h('Poptip', {
                //     props: {
                //         confirm: true,
                //         'ok-text': "确定",
                //         'cancel-text': "取消",
                //         type: 'error',
                //         size: 'large',
                //         transfer:true,
                //         title: `你确定要${params.row.tag == 0 || params.row.tag == 3 || params.row.status == 2 ? '取消撤销' : '撤销'}吗?`
                //     },
                //     on: {
                //         'on-ok': () => {
                //         this.modifyRecordStatus(params.row.id,params.row.status,params.row.tag, params.row.isRight)
                //         }
                //     }
                //     }, [
                //         h('Button',{
                //         props:{
                //             type:'primary',
                //             size:'small',
                //             disabled: this.isDisabled(params.row)
                //         },
                //         style:{
                //             marginRight:'5px',
                //             width:'65px'
                //         },
                //         on:{
                //             click:()=>{
                //             }
                //         }
                //         },params.row.tag == 0 || params.row.tag == 3 || params.row.status == 2 ? '取消撤销' : '撤销')
                //     ])
                // }
            })
        }
    },
    beforeDestroy(){
		clearTimeout(this.timeout)
	},
	mounted(){
        const t = function(val){
            this.selTargetName = val;
            this.getAttackSuccess(null,null,val)
        }.bind(this);
	    const setTargetName = function(val){
	    	this.selTargetName = val.currentTarget.value;
	    }.bind(this);
        this.getAttackSuccess();
        this.getQuestionList()
        this.getTopicsList()
    },
  methods:{
          byStatus(val) {
              this.status = val;
              this.getAttackSuccess();
          },
        getQuestionList() {
            queryCtfTarget(this.$route.query.id, {
                pageIndex:1,
                pageSize:2147483647
            }).then(data => {
               console.log('this.data',data);
                if(data.code==1){
                    this.questionList = data.data.items || data.data;
                }else{
                    this.targetTeamList = []
                }
            }).catch(error => {
                this.$Message.error('获取列表失败');
            })
        },


        getTopicsList() {
            let apiFun = getTargetTeamList_new
            if(this.$route.name.includes('awdDrillDetail')){
              apiFun = getTargetTeamList
            }
            
          
            apiFun({
              sceneId: this.$route.query.id,
              pageIndex:1,
              pageSize:2147483647
            }).then(data => {
              console.log('this.getTargetTeamList_new',apiFun,data);
                if(data.code==1){
                    this.topicsList = data.data.items || data.data;
                }else{
                    this.targetTeamList = []
                }
            }).catch(error => {
                this.$Message.error('获取列表失败');
            })
        },
      	getAttackSuccessById(id) {
            this.selName = this.getTeamNameById(id)
            this.getAttackSuccess()
        },
      	getAttackSuccessByQuestion(id) {
          let obj = this.questionList.find(item => item.id === id)
          this.selTargetName = obj ? obj.name : '';
          this.getAttackSuccess(null,null)
      	},
        getAttackSuccessByTopics(id) {
          let obj = this.topicsList.find(item => item.id === id)
          this.selTargetName = obj ? obj.name : '';
          this.getAttackSuccess(null,null)
      	},
        // 查询全部的提交记录，用于轮训哪些提交不允许撤销
        async getAllAttackSuccess() {
          return new Promise(resolve => {
              this.disabledDestroy = false;
              submitRecord({
                pageIndex: 1,
                pageSize: 10
              }).then(data=>{
                if(data.code==1){
                  this.allList = data.data.items
                }
              }).finally(() => {
                  resolve()
              })
          })
        },
        // 判断是否禁用撤销按钮
        isDisabled(obj) {
          if (!this.allList) {
            return false
          }
          let list = this.allList.filter(item => item.targetId === obj.targetId && item.teamId === obj.teamId)
          if (list.length < 2) { // 最多一条数据，不禁用
            return false
          } else { // 多条数据时，存在正确的提交，禁用错误提交的撤销，否则不禁用
            if (list.some(subItem => subItem.isRight === 1)) {
              return obj.isRight !== 1
            } else {
              return false
            }
          }
        },
    getAttackSuccess(page,pageSize,querytime){
      let _this = this;
      let pages = page || 1;
      let rows = pageSize||_this.PZ|| 10;
      this.$set(this.initObj.Page, 'currentPage', pages)
      let id = '';
      if(!_this.$route.query.id){
        return
      }
      let params={
        pageIndex : pages,
        pageSize : rows,
        sceneId:_this.$route.query.id,
//      scoreType:1
      };
      if(this.selName){
        params.teamName =  this.selName;
      }
      if(this.isright){
        params.isRight = this.isright;
      }
      if(this.selTargetName){
        params.targetName =  this.selTargetName;
      }
      if (this.status) {
          params.status =  this.status;
      }
    /*  if(this.status){
        params.status = this.status
      }*/
//    if(querytime){
//      params.createtime = querytime[0];
//      params.lastupdatetime = querytime[1];
//    }
      submitRecord(params).then(async data=>{
        if(data.code==1){
          await this.getAllAttackSuccess()
          _this.initObj.Table.listData = data.data.items;
          _this.initObj.Page.total = data.data.total;
          if(this.poll){ //如果需要轮询
          	    clearTimeout(this.timeout)
		    	this.timeout = setTimeout(() => {
		    		this.getAttackSuccess(page, pageSize);
		    	},10000)
		    }
        }
      })
    },
    cancelstatusFilter(val){
      let str='';
      switch(val){
        case '0':str = '已统计';break;
        case '1':str = '取消攻击得分';break;
        case '2':str = '得分未统计';break;
        default:str='得分未统计';break;
      }
      return str;
    },
    modifyRecordStatus(id,status,tag,isRight){
      let mStatus
      if (tag == 1 && isRight == 1) {
        if (isRight == 1) { // 答题正确时，撤销，取消撤销的状态切换
          mStatus = status == 2 ? 1 : 2
        } else { // 题目错误，撤销操作
          mStatus = 3
        }
      } else { // 错误题目，取消撤销
        if (isRight == 1) {
          mStatus = 4
        } else {
          mStatus = 3
        }
      }
    	modifyUserSubmitRecordStatus(id,mStatus).then(data => {
    		if(data.code == 1){
    			this.getAttackSuccess();
    		} else {
                this.$Message.warning(data.message)
            }
    	})
    }
    },
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }
  .targetHeader{
    padding: 10px;
    margin-bottom: 10px;
  }
</style>
